// index.js
const defaultAvatarUrl = '../../images/user.png'
const http = require('../../utils/request')
const { taskApi } = require('../../utils/api')

Page({
  data: {
    motto: 'Hello World',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    greeting: '上午好',
    tasks: [],
    pendingTasks: []
  },
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  onInputChange(e) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  onLoad() {
    // 获取缓存的用户信息
    const userInfo = wx.getStorageSync('userInfo')
    // 设置用户信息
    this.setData({ 
      userInfo: {
        ...userInfo,
        userName: userInfo.userName || '波妞',
        roleCode: userInfo.roleCode || '1003',
        regionName: userInfo.regionName || '北京市北五环奥体中心'
      }
    })
    
    // 设置问候语
    this.setGreeting()
    
    // 获取任务列表
    this.getTaskList()
    
    // 如果是维修员，查询待办工单
    if(userInfo.roleCode === '1003') {
      this.getPendingTasks()
    }
  },
  // 设置问候语
  setGreeting() {
    const hour = new Date().getHours()
    let greeting = '上午好'
    
    if(hour < 6) {
      greeting = '凌晨好'
    } else if(hour < 9) {
      greeting = '早上好'
    } else if(hour < 12) {
      greeting = '上午好'
    } else if(hour < 14) {
      greeting = '中午好'
    } else if(hour < 17) {
      greeting = '下午好'
    } else if(hour < 19) {
      greeting = '傍晚好'
    } else {
      greeting = '晚上好'
    }
    
    this.setData({ greeting })
  },
  // 获取任务列表
  getTaskList() {
    const userInfo = this.data.userInfo
    // 构造查询参数
    const params = {
      pageIndex: 1,
      pageSize: 10
    }
    
    // 根据不同角色设置不同的查询条件
    switch(userInfo.roleCode) {
      case '1001': // 工单管理员可以看到所有工单
        break;
      case '1002': // 运营员只看自己区域的工单
        params.regionId = userInfo.regionId;
        break;
      case '1003': // 维修员只看分配给自己的工单
        params.userId = userInfo.userId;
        params.isRepair = true;
        break;
    }
    
    http.get(taskApi.search(params))
      .then(res => {
        this.setData({
          tasks: res.records?.map(task => ({
            ...task,
            createTime: this.formatTime(task.createTime)
          })) || []
        })
      })
      .catch(err => {
        wx.showToast({
          title: err || '获取任务列表失败',
          icon: 'none'
        })
      })
  },
  // 格式化时间
  formatTime(timestamp) {
    if(!timestamp) return ''
    const date = new Date(timestamp)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  },
  // 查看工单详情
  onTaskDetail(e) {
    const taskId = e.currentTarget.dataset.id
    const taskCode = e.currentTarget.dataset.code
    wx.navigateTo({
      url: `/pages/task/detail/index?id=${taskCode}`
    })
  },
  // 退出登录
  onLogout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if(res.confirm) {
          wx.clearStorageSync()
          wx.reLaunch({
            url: '/pages/login/login'
          })
        }
      }
    })
  },
  // 获取待办工单
  getPendingTasks() {
    const userInfo = this.data.userInfo
    const params = {
      userId: userInfo.userId,
      isRepair: true,
      status: 1  // 待办状态
    }
    
    http.get(taskApi.search(params))
      .then(res => {
        // 处理待办工单数据
        const pendingTasks = res.currentPageRecords?.map(task => ({
          ...task,
          createTime: this.formatTime(task.createTime),
          address: task.addr, // 后端返回的是 addr 字段
          taskCode: task.taskCode,
          innerCode: task.innerCode,
          userName: task.userName,
          id: task.taskId // 后端返回的是 taskId
        })) || []

        this.setData({
          pendingTasks
        })

        // 如果有待办工单，显示提示
        if(pendingTasks.length > 0) {
          wx.showToast({
            title: `您有${pendingTasks.length}个待办工单`,
            icon: 'none',
            duration: 2000
          })
        }
      })
      .catch(err => {
        console.error('获取待办工单失败:', err)
      })
  }
})
